package com.wanpinghui.supplier.user;

import android.content.DialogInterface;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.text.style.RelativeSizeSpan;
import android.view.View;
import android.widget.TextView;

import com.wanpinghui.supplier.R;
import com.wanpinghui.supplier.common.BaseActivity;
import com.wanpinghui.supplier.oauth.LoginUtil;
import com.wanpinghui.supplier.user.adapter.PlansListAdapter;
import com.wanpinghui.supplier.widgets.TitlePanelLayoutUser;
import com.wanpinghui.wphlibrary.WPHSdk;
import com.wanpinghui.wphlibrary.common.dialog.BaseDialogManager;
import com.wanpinghui.wphlibrary.model.base.pay.PayManager;
import com.wanpinghui.wphlibrary.model.oauth.OAuthService;
import com.wanpinghui.wphlibrary.model.oauth.bean.UserBean;
import com.wanpinghui.wphlibrary.model.user.bean.RechargePlansBean;
import com.yunshl.yunshllibrary.recyclerview.OnItemClickListener;
import com.yunshl.yunshllibrary.utils.TimeUtil;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;

import retrofit.callback.YRequestCallback;

/**
 * 功能描述 我的套餐
 * author:caitiangui
 * time:2017/11/27
 */
@ContentView(R.layout.layout_activity_minepackage)
public class MinePackageActivity extends BaseActivity implements PayManager.PayResultListener {

    @ViewInject(R.id.tpl_title)
    private TitlePanelLayoutUser mLayoutTitle;
    @ViewInject(R.id.recv_plans_list)
    private RecyclerView mRecyclerViewPlans;
    @ViewInject(R.id.tv_pay_type)
    private TextView textViewPayType;
    @ViewInject(R.id.tv_end_date)
    private TextView textViewEndDate;
    @ViewInject(R.id.tv_bid_point)
    private TextView textViewBidPoint;
    @ViewInject(R.id.tv_sms_point)
    private TextView textViewSmsPoint;


    private PlansListAdapter mAdapter;
    private UserBean mUserBean;
    private boolean shouldResult;
    private RechargePlansBean createPlansBean;

    @Override
    public String getName() {
        return null;
    }

    @Override
    public boolean isBar() {
        return false;
    }

    @Override
    public void initViews() {
        if (LoginUtil.loginFilter(this)) {
            mRecyclerViewPlans.setLayoutManager(new LinearLayoutManager(this));
            mAdapter = new PlansListAdapter(this);
            mRecyclerViewPlans.setAdapter(mAdapter);
            if (getIntent() != null) {
                shouldResult = getIntent().getBooleanExtra("result", false);
            }
        }
    }

    @Override
    public void bindEvents() {
        mLayoutTitle.setOnClickBacktrack(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        mAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                createPlansBean = mAdapter.getData(position);
                payPlans();
            }
        });
    }

    private void payPlans() {
        if (createPlansBean != null) {
            PayManager.getInstance().payByWechat(createPlansBean.getId(), new YRequestCallback() {
                @Override
                public void onSuccess(Object var1) {

                }

                @Override
                public void onFailed(int var1, String message) {
                    showWarningText(message);
                }

                @Override
                public void onException(Throwable var1) {
                    var1.printStackTrace();
                }
            });
        }
    }

    @Override
    public void initData() {
        getUserInfo();
//        WPHSdk.getService(UserInfoService.class).getPlansList(new YRequestCallback<List<RechargePlansBean>>() {
//            @Override
//            public void onSuccess(List<RechargePlansBean> var1) {
//                mAdapter.setDatas(var1);
//            }
//
//            @Override
//            public void onFailed(int var1, String message) {
//
//            }
//
//            @Override
//            public void onException(Throwable var1) {
//
//            }
//        });
    }

    private void getUserInfo() {
        mUserBean = WPHSdk.getService(OAuthService.class).getUserInfo(new YRequestCallback<UserBean>() {
            @Override
            public void onSuccess(UserBean var1) {
                mUserBean = var1;
                setData(mUserBean);
            }

            @Override
            public void onFailed(int var1, String message) {
                mUserBean = WPHSdk.getService(OAuthService.class).getUserInfo(null);
                setData(mUserBean);
            }

            @Override
            public void onException(Throwable var1) {
                mUserBean = WPHSdk.getService(OAuthService.class).getUserInfo(null);
                setData(mUserBean);
            }
        });
    }

    private void setData(UserBean userBean) {
        if (textViewBidPoint != null) {
            if (userBean != null && userBean.getPack() != null) {
                textViewBidPoint.setText(Integer.toString(userBean.getPack().getBid_point()));
                textViewSmsPoint.setText(Integer.toString(userBean.getPack().getSms_point()));
                textViewEndDate.setText("套餐的有效期至" + TimeUtil.formatTime(userBean.getPack().getEnd_date()));
            }
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        PayManager.getInstance().addPayResultListener(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        PayManager.getInstance().removePayResultListener(this);
    }

    @Override
    public void paySuccess(long orderId, int bidPoint) {
        getUserInfo();
        if (shouldResult) {
            setResult(RESULT_OK);
            finish();
        } else {
            long timeL = 0;
            if (mUserBean != null && mUserBean.getPack() != null) {
                String endTime = mUserBean.getPack().getEnd_date();
                long time = TimeUtil.parseTime(endTime, "yyyy-MM-dd");
                timeL = time - System.currentTimeMillis();
                if (timeL < 0) {
                    timeL = 0;
                }
            }
            String string = "已新增" + createPlansBean.getBid_point() + "个汇币，";
            SpannableString spannableString = new SpannableString(string);
            spannableString.setSpan(new ForegroundColorSpan(ContextCompat.getColor(MinePackageActivity.this, R.color.colorTextPrimaryHint)), string.length() - 9, string.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
            spannableString.setSpan(new RelativeSizeSpan(0.93f), string.length() - 9, string.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
            BaseDialogManager.getInstance().getBuilder(this)
                    .setIcon(ContextCompat.getDrawable(this, R.drawable.lib_toast_icon_ok))
                    .setTitle("支付成功")
                    .setMessage(spannableString)
                    .setRightButtonText("知道了")
                    .setOnClickListener(new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    })
                    .create()
                    .show();
        }
        createPlansBean = null;
    }

    @Override
    public void payFail(int code, String message) {
        BaseDialogManager.getInstance().getBuilder(this)
                .setIcon(ContextCompat.getDrawable(this, R.drawable.lib_toast_icon_mistake))
                .setTitle("支付失败")
                .setMessage("您支付失败或取消支付")
                .setRightButtonText("重新支付")
                .setOnClickListener(new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (which == BaseDialogManager.RIGHT_BUTTON) {
                            payPlans();
                        }
                        dialog.dismiss();
                    }
                })
                .create()
                .show();
    }
}
